//加解密
import {
  decryptECB,
  encryptECB
} from "../crypt/index"

//私钥
const privateKey = 'ARilvk7D3Phq766hQHilvk7D3PhqU57h';

//获取session
export const postSession = (requestParamsObj) => {
  //1、map转对象
  const paramsMap = Object.fromEntries(requestParamsObj.requestBodyMap);
  //2、对象转字符串
  const str = JSON.stringify(paramsMap);
  //3、字符串加密
  const body = encryptECB(str, privateKey);
  return new Promise((resolve, reject) => {
    wx.request({
      url: requestParamsObj.url,
      timeout: 30 * 1000,
      method: 'post',
      dataType: '其他',
      responseType: 'text',
      header: {
        'content-type': 'application/json', // 默认值
        'sessionId': requestParamsObj.sessionId, //自定义请求头
      },
      data: body,
      success: (res) => {
        const response = res.data
        const code = res.statusCode
        if (code === 200) {
          //响应成功
          if (isJSON(response)) {
            //错误处理:非密文->转json对象
            const errorData = JSON.parse(response);
            resolve(errorData)
          } else {
            //密文
            //1、私钥解密
            const str = decryptECB(response, privateKey);
            //2、字符串转对象
            const newData = JSON.parse(str);
            resolve(newData)
          }
        } else {
          const err = {
            errMsg: response,
            errno: code
          }
          reject(err)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

function isJSON(str) {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}